package com.DosonLeung.homeschoolcommunication.Models;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.DosonLeung.homeschoolcommunication.Components.TestAdapter;
import com.DosonLeung.homeschoolcommunication.Constant.SystemConstant;
import com.DosonLeung.homeschoolcommunication.Constant.UserConstant;
import com.DosonLeung.homeschoolcommunication.Modules.CameraModule.CameraActivity;
import com.DosonLeung.homeschoolcommunication.Modules.SystemAlbumModule.SystemAlbumActivity;
import com.DosonLeung.homeschoolcommunication.R;
import com.DosonLeung.homeschoolcommunication.SQLite.ChatsDB;
import com.DosonLeung.homeschoolcommunication.SQLite.MembersDB;
import com.DosonLeung.homeschoolcommunication.Utils.AlbumUtil;
import com.DosonLeung.homeschoolcommunication.Utils.RecordUtil;
import com.DosonLeung.homeschoolcommunication.Utils.StorageUtil;
import com.DosonLeung.homeschoolcommunication.Utils.TimeUtil;
import com.DosonLeung.homeschoolcommunication.Views.ChatLayout;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by DosonLeung on 2014/10/21.
 */
public class ChatModel {

    ChatModel self = this;
    //运行该model的Activity
    private Activity app;
    //聊天数据库SQLiteOpenHelper对象
    private ChatsDB DBhelper ;
    //联系人数据库
    private MembersDB membersDB;
    //第一次获取聊天记录的最大条数
    private final int MAX_RECORD_SUM = 50;
    //第二次以后获取聊天记录的最大条数
    private final int MAX_HISTORY_SUM = 10;
    //聊天对象的ID
    private final String target;
    //聊天对象的头像地址
    private final String avatar_path;
    //聊天类型（true：班级 false：个人）
    private final boolean type;
    //聊天记录的ListView
    private ChatLayout chatLayout;
    //聊天记录数组,视图的数据
    public List<Map<String,String>> chatList;
    //视图的适配器
    private TestAdapter chatAdapter;
    //bind view 时需要从chatList取的键
    private final String[] key = new String[]{"icon","time","content","url","url"};
    //bind view 时需要插入数据的视图id,l指聊天我方气泡，r指聊天对方气泡。
    private final int[] lto = new int[]{R.id.chatlist_litem_icon,R.id.chatlist_litem_time,R.id.chatlist_litem_text,R.id.chatlist_litem_image,R.id.chatlist_litem_voice};
    private final int[] rto = new int[]{R.id.chatlist_ritem_icon,R.id.chatlist_ritem_time,R.id.chatlist_ritem_text,R.id.chatlist_ritem_image,R.id.chatlist_ritem_voice};
    //负责点对点的聊天记录的handler
    private Handler mHandler;
    //与service通讯的Handler
    private Handler serviceHandler;
    //相片来源 true photo false album
    public boolean photo = false;

    public ChatModel(Activity app,String target,String avatar_path, final ChatLayout chatLayout, final boolean type){//true为班级 群发消息时：target和avatar_path为groupchat,
        this.app = app;
        this.avatar_path = avatar_path;
        this.type = type;
        this.chatLayout = chatLayout;
        this.DBhelper = new ChatsDB(app, StorageUtil.getChatDir().toString()+"/"+target+".db3",target,1);//数据库名有两种：cid+UserConstant.USER_ID/uid
        //重新修改正target
        if(type){//群发忽略这步
            if(UserConstant.USER_CHARACTER.equals("patriarch"))
                this.target = target;
            else
                this.target = target.substring(0, target.length() - UserConstant.USER_ID.length());//老师的话，target改为班级的cid
        }else{//群发
            this.target = target;
        }
        if(target.equals("groupchat"))//群发
            this.chatList = new LinkedList<Map<String, String>>();
        else
            this.chatList = retrieveChatList();
        this.mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1003:
                        //录音中
                        break;
                    case 1004:
                        //录音完成
                        RecordUtil.stopRecording();
                        break;
                    case 0x202:
                        asyncNotifyView();
                        break;
                }
            }
        };
        if(chatList!=null){
            this.chatAdapter = new TestAdapter(self,chatLayout,chatList, avatar_path,R.layout.chatlist_litem,R.layout.chatlist_ritem,key,lto,rto,mHandler);
            chatLayout.setAdapter(this.chatAdapter);
        }
    }

    public Handler getMHandler(){
        return this.mHandler;
    }

    public TestAdapter getChatAdapter() {
        return chatAdapter;
    }

    public Activity getApp(){
        return app;
    }

    public String getTarget() {
        return target;
    }

    public boolean getType() {
        return type;
    }

    public void notifyAllViews(){
        List<Map<String,String>> list = retrieveChatList();
        int Lsize = list.size();
        int Csize = this.chatList.size();
        if(Lsize > Csize) {
            for (int i = Csize; i < Lsize ; i++) {
                this.chatList.add(list.get(i));
            }
        }
        this.chatAdapter.notifyDataSetChanged();
        this.chatLayout.smoothScrollToButtom();
    }

    /**
     * 当ChatAdapter的一个图片加载线程完成后，通知chatModel调用该方法
     * 异步更改其中的图片的内容
     * */
    private void asyncNotifyView(){
        int lastIndex = this.chatAdapter.getBitmapList().size() - 1;
        final HashMap<String, Object> item = this.chatAdapter.getBitmapList().get(lastIndex);
        Integer index = (Integer) item.get("index");
        Bitmap bitmap = (Bitmap) item.get("bitmap");
        ImageView image = this.chatAdapter.getImageList().get(index);
        image.setImageBitmap(bitmap);
        image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlbumUtil.openInAlbum(app,(String)item.get("url"));
            }
        });
    }

    public boolean getPhotoFromAlbum(Activity app){
        try {
            Intent intent = new Intent(app, SystemAlbumActivity.class);
            app.startActivityForResult(intent, SystemConstant.GET_PHOTO_FROM_ALBUM);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean getPhotoFromCamera(Activity app){
        try {
            Intent intent = new Intent(app, CameraActivity.class);
            intent.putExtra("target",target);
            app.startActivityForResult(intent, SystemConstant.GET_PHOTO_FROM_CAMERA);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    //发送文字消息的时间由调用该方法决定
    public boolean sendMessage(String Message,String level){
        if(Message.length()==0){
            Toast.makeText(app,"不可发送空消息",Toast.LENGTH_SHORT).show();
            return false;
        }else if(Message.length()<1024) {
            String time = TimeUtil.getTime();
            HashMap<String, String> item = new HashMap<String, String>();
            item.put("uid", UserConstant.USER_ID);//如果是班级信息，则uid＝cid＋uid
            item.put("contentType", "text");
            item.put("time", time);
            item.put("content", Message);
            item.put("length",type?target:"");
            item.put("url", "");
            item.put("contentLevel",level);
            HashMap<String, String> memberItem = new HashMap<String, String>();
            memberItem.put("uid", type?(target+UserConstant.USER_ID):target);
            memberItem.put("lasttime", time);
            memberItem.put("lastnote", Message);
            memberItem.put("lastnotetype", "text");
            DBhelper.insertChattingData(item);
            membersDB = new MembersDB(app, StorageUtil.getChatDir().toString() + "/" + "members.db3", 1);
            membersDB.updateMembersPart(memberItem);
            membersDB.close();
            sendByMessage(item,"text");
            addTextToView(item);
            return true;
        }else{
            Toast.makeText(app,"您发送的消息超出长度限制，请分条发送",Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    //从相册取出无须保存
    public void sendPhotoFromAlbum(String url,String level){
        String time = TimeUtil.getTime();
        HashMap<String, String> item = new HashMap<String, String>();
        item.put("uid", UserConstant.USER_ID);
        item.put("contentType","image");
        item.put("time", time);
        item.put("content","");
        item.put("url",url);
        item.put("length",type?target:"");
        item.put("contentLevel",level);
        HashMap<String, String> memberItem = new HashMap<String, String>();
        memberItem.put("uid", type?target+UserConstant.USER_ID:target);
        memberItem.put("lasttime", time);
        memberItem.put("lastnote", "[图片]");
        memberItem.put("lastnotetype", "image");
        DBhelper.insertChattingData(item);
        membersDB = new MembersDB(app, StorageUtil.getChatDir().toString() + "/" + "members.db3", 1);
        membersDB.updateMembersPart(memberItem);
        membersDB.close();
        sendByMessage(item,"image");
        addAlbumToView(item);
    }

    //从相册获得照片的地址，请求service发送
    public void sendPhotoFromCamera(String url,String level){
        String time = TimeUtil.getTime();
        HashMap<String, String> item = new HashMap<String, String>();
        item.put("uid", UserConstant.USER_ID);
        item.put("contentType","image");
        item.put("time", time);
        item.put("content","");
        item.put("url",url);
        item.put("length",type?target:"");
        item.put("contentLevel",level);
        HashMap<String, String> memberItem = new HashMap<String, String>();
        memberItem.put("uid", type?target+UserConstant.USER_ID:target);//从type判断是否为uid/cid
        memberItem.put("lasttime", time);
        memberItem.put("lastnote", "[图片]");
        memberItem.put("lastnotetype", "image");
        DBhelper.insertChattingData(item);
        membersDB = new MembersDB(app, StorageUtil.getChatDir().toString() + "/" + "members.db3", 1);
        membersDB.updateMembersPart(memberItem);
        membersDB.close();
        sendByMessage(item,"image");
        addPhotoToView(item);
    }

    public void sendVoice(String url,String level){
        String time = TimeUtil.getTime();
        HashMap<String, String> item = new HashMap<String, String>();
        item.put("uid", UserConstant.USER_ID);
        item.put("contentType","audio");
        item.put("time", time);
        item.put("content","");
        item.put("url",url);
        item.put("length",type?target:"");
        item.put("contentLevel",level);
        HashMap<String, String> memberItem = new HashMap<String, String>();
        memberItem.put("uid", type?target+UserConstant.USER_ID:target);
        memberItem.put("lasttime", time);
        memberItem.put("lastnote", "[语音]");
        memberItem.put("lastnotetype", "audio");
        DBhelper.insertChattingData(item);
        membersDB = new MembersDB(app, StorageUtil.getChatDir().toString() + "/" + "members.db3", 1);
        membersDB.updateMembersPart(memberItem);
        membersDB.close();
        sendByMessage(item, "audio");
        addVoiceToView(item);
    }

    public void sendExpression(int id){
        String time = TimeUtil.getTime();
        HashMap<String, String> item = new HashMap<String, String>();
        HashMap<String, String> memberItem = new HashMap<String, String>();
        item.put("uid", UserConstant.USER_ID);
        item.put("contentType","expression");
        item.put("time", time);
        item.put("content","");
        item.put("url","");
        item.put("length","");
        item.put("length",type?target:"");
        memberItem.put("uid", type?target+UserConstant.USER_ID:target);
        memberItem.put("lasttime", time);
        memberItem.put("lastnote", Integer.toString(id));
        memberItem.put("lastnotetype", "express");
        DBhelper.insertChattingData(item);
        membersDB = new MembersDB(app, StorageUtil.getChatDir().toString() + "/" + "members.db3", 1);
        membersDB.updateMembersPart(memberItem);
        membersDB.close();
        //sendByMessage(item);
        addExpressionToView("me",id);
    }

    //发送消息第三部，在视图上显示文字消息
    private void addTextToView(HashMap<String, String> item){
        item.remove("uid");
        item.put("uid", UserConstant.USER_ID);//恢复发送人信息，因为这里只是一个item，需要本人的头像
        this.chatList.add(item);
        this.chatAdapter.notifyDataSetChanged();
        this.chatLayout.smoothScrollToButtom();
    }

    //发送消息第三部，在视图上显示图片消息
    private void addPhotoToView(HashMap<String, String> item){
        item.remove("uid");
        item.put("uid", UserConstant.USER_ID);//恢复发送人信息，因为这里只是一个item，需要本人的头像
        this.chatList.add(item);
        this.chatAdapter.notifyDataSetChanged();
        this.chatLayout.smoothScrollToButtom();
    }

    //发送消息第三部，在视图上显示相册消息
    private void addAlbumToView(HashMap<String, String> item){
        item.remove("uid");
        item.put("uid", UserConstant.USER_ID);//恢复发送人信息，因为这里只是一个item，需要本人的头像
        this.chatList.add(item);
        this.chatAdapter.notifyDataSetChanged();
        this.chatLayout.smoothScrollToButtom();
    }

    //发送消息第三部，在视图上显示音频消息
    private void addVoiceToView(HashMap<String, String> item){
        item.remove("uid");
        item.put("uid", UserConstant.USER_ID);//恢复发送人信息，因为这里只是一个item，需要本人的头像
        this.chatList.add(item);
        this.chatAdapter.notifyDataSetChanged();
        this.chatLayout.smoothScrollToButtom();
    }

    private void addExpressionToView(String target, int id) {

    }

    private List<Map<String,String>> retrieveChatList(){
        List<Map<String,String>> chatlist = null;
        int size = DBhelper.getCount();
        if(size<=MAX_RECORD_SUM)
            chatlist = DBhelper.getChattingData();
        else
            chatlist = DBhelper.getChattingData(size-MAX_RECORD_SUM,size-1);
        return chatlist;
    }

    private boolean isDBHelperExist() {
        if(DBhelper!=null)
            return true;
        else
            return false;
    }

    public void retrieveHistory() {
        int Csize = chatList.size();
        int Count = DBhelper.getCount();
        LinkedList<Map<String, String>> list = new LinkedList<Map<String, String>>();
        if (Count - Csize == 0)
            Toast.makeText(app,"没有聊天记录了",Toast.LENGTH_SHORT).show();
        else if (MAX_HISTORY_SUM > Count - Csize)
            list = DBhelper.getChattingData(0, Count - Csize - 1);
        else if (MAX_HISTORY_SUM < Count - Csize)
            list = DBhelper.getChattingData(Count - MAX_HISTORY_SUM - Csize, Count - Csize);
        chatAdapter.addNotesAtFirst(list);
    }

    public void closeDBHelper(){
        if(isDBHelperExist())
        this.DBhelper.close();
    }

    public void setServiceHandler(Handler serviceHandler) {
        this.serviceHandler = serviceHandler;
    }

    //此处的会进行格式转换
    private void sendByMessage(HashMap<String, String> item,String type){
        Bundle data = new Bundle();
        data.putString("sender_name",UserConstant.USER_NAME);//发送者名称
        data.putString("sender_uid",item.get("uid"));//发送者id，即USER_ID
        data.putString("uid",this.type?"":target);//群发消息走这里
        data.putString("cid",this.type?target:"");
        data.putString("contentType",item.get("contentType"));
        data.putString("contentTime",item.get("time"));
        data.putString("content",item.get("content"));
        data.putString("url",item.get("url"));
        data.putString("contentLevel",item.get("contentLevel"));
        data.putString("contentLength",item.get("length"));//存放cid或者""，群发消息为""
        Message msg = new Message();
        msg.setData(data);
        if(type.equals("text"))
            msg.what = 0x202;
        else if(type.equals("image"))
            msg.what = 0x203;
        else if(type.equals("audio"))
            msg.what = 0x204;
        serviceHandler.sendMessage(msg);
    }

}
